﻿using d1Common.Interface;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.Routing;

namespace d1Common.WebController
{
    public class Authorize0Attribute : FilterAttribute, IAuthenticationFilter
    {
        public Authorize0Attribute()
        {
            
        }
        private const string AccessTokenName = "accessToken";

        //支持OAuth Authorsize,get 参数，cookie三种方式认证
        public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            string _token;
            if (context.ActionContext.Request.Headers.Authorization != null) 
            {
                if (context.ActionContext.Request.Headers.Authorization.Scheme.ToLower() != "bearer")
                {
                    throw new UserException("只支持Bearer方式的用户认证");
                }
                _token = context.ActionContext.Request.Headers.Authorization.Parameter;
            }
            else
            {
                var value = context.Request.GetQueryNameValuePairs().FirstOrDefault(u=>u.Key==AccessTokenName);
                if (value.Value != null)
                {
                    _token = value.Value.ToString();
                }
                else
                {
                    var cookie = context.Request.Headers.GetCookies(AccessTokenName);
                    if (cookie == null || cookie.Count <=0 || cookie[0].Cookies.Count <= 0) throw new UserException( "需要登录认证", HttpStatusCode.Unauthorized);
                    _token = cookie[0].Cookies[0].Value;
                }                                
            }
            string _serviceToken = doServices.Instance.DoConfig.readLocalConfig("ServiceToken", null);
            if (_serviceToken==null || _serviceToken != _token) throw new UserException("服务认证失败", HttpStatusCode.Unauthorized);

            GenericIdentity identity = new GenericIdentity("$ServiceAuth$");
            context.Principal = new GenericPrincipal(identity, new string[0]);
            
            return Task.FromResult<object>(null);
        }

        public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
        {            
            return Task.FromResult<object>(null);
        }       
    }
}